<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Console\Command;

class test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $url = "https://doptest-api.dfyoo.com";
        $appid = 100012;
        $api_key = "tickettest";
        $api_secret = "aaaaaaaa";

//        $url = "https://doptest-api.dfyoo.com";
//        $appid = 100012;
//        $api_key = "247187_Ticket";
//        $api_secret = "tyONC2Z7YGgdjq0pOCiX";

        $uri = "/Ticket/scenicList";
        $param = [];
        $buildSign = function(array $params)use($param,$api_secret){
            $sign_params = $this->getSignParams($params,$param);
            ksort($sign_params);
            $str = "";
            $str_arr = [];
            foreach ($sign_params as $key=> $value){
                $str_arr[$key] = "{$key}={$value}";
            }
            $str = implode("&",$str_arr);
            $build = "{$api_secret}&{$str}&{$api_secret}";
//            dd($build);
            $sign = strtoupper(md5($build));
//            dd($sign);
            return $sign;
        };
        $params = [
            "apiKey"=>$api_key,
            "data"=>[
                "pageSize"=>1,
                "page"=>1,
                "key"=>"乌鲁木齐"
            ],
            "timestamp"=>Carbon::now()->toDateTimeString()
        ];

        $sign = $buildSign($params);
        $params['sign'] = $sign;
        $client = new Client([
            'verify'=>false
        ]);

        $this->info(json_encode($params,64|256));
        $req = $client->post($url.$uri,[
            'json'=>$params
        ]);

        dd($req->getBody()->getContents());
    }

    /**
     * @param array $params
     * @param array $ret
     * @return array
     */
    private function getSignParams(array $params, array &$ret): array
    {
        foreach ($params as $key => $value) {
                if(!$value){
                    continue;
                }
                if (!is_array($value)) {
                    $ret[$key] = $value;
                } else {
                    $this->getSignParams($value,$ret);
                }

        }
        return $ret;
    }
}
